package cn.edu.zzuli.nothinglink.service.impl;

import cn.edu.zzuli.nothinglink.constant.TokenConst;
import cn.edu.zzuli.nothinglink.entity.R;
import cn.edu.zzuli.nothinglink.entity.Teachers;
import cn.edu.zzuli.nothinglink.mapper.TeachersMapper;
import cn.edu.zzuli.nothinglink.service.TeachersService;
import cn.edu.zzuli.nothinglink.utils.RedisUtil;
import cn.edu.zzuli.nothinglink.utils.TokenUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author suzyyy
 * @since 2021-04-08
 */
@Service
public class TeachersServiceImpl extends ServiceImpl<TeachersMapper, Teachers> implements TeachersService {

    @Resource
    TeachersMapper teachersMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public R teaLogin(JSONObject json) {
        //从数据库中获取当前用户
        Teachers teacher = teachersMapper.selectOne(
                new LambdaQueryWrapper<Teachers>().eq(Teachers::getTeaNumber,
                        json.getString("teaNumber"))
        );

        if (teacher != null && teacher.getTeaPassword().equals(json.getString("password"))) {
            //验证成功后，返回创建的 token
            Long currentTimeMillis = System.currentTimeMillis();
            String token= createToken(teacher.getTeaId());

            return R.success().add("tea", teacher.setTeaPassword("")).add("token", token);
        }
        return R.error().add("error", "请检查工号/密码是否有误");
    }

    public R registerTea(Teachers teacher) {
        boolean save = this.save(teacher);
        if (save) {
            String token= createToken(teacher.getTeaId());
            return R.success().add("tea", teacher.setTeaPassword("")).add("token", token);
        }
        return R.error().add("error", "注册失败");
    }

    private String createToken(Integer teaId) {
        Long currentTimeMillis = System.currentTimeMillis();
        String token= TokenUtil.sign(teaId.toString(),
                TokenConst.TEA_ROLE.getKey(), currentTimeMillis);
        //设置token信息到redis中，方便进行校验
        redisUtil.set(TokenConst.TEA_REFRESH_TOKEN.getKey() + teaId.toString(),
                currentTimeMillis,TokenUtil.REFRESH_EXPIRE_TIME);
        return token;
    }

}
